<template>
  <div class="user-setting-container">
    <h1 class="user-setting-title">账号信息设置</h1>
    <div class="user-setting-container-avatar">
      <a-upload
        data-custom-avatar-upload
        v-model:file-list="fileList"
        name="avatar"
        list-type="picture-card"
        class="avatar-uploader"
        :show-upload-list="false"
        :before-upload="beforeUpload"
        @change="handleChange"
        :customRequest="customUpload"
      >
        <!-- 有头像时显示头像 + 相机图标 -->
        <div
          v-if="imageUrl"
          class="avatar-container"
          @mouseenter="showCamera = true"
          @mouseleave="showCamera = false"
        >
          <img :src="imageUrl" alt="avatar" class="avatar-img" />
          <div v-if="showCamera" class="camera-overlay" @click="triggerUpload">
            <plus-outlined style="font-size: 32px; color: #fff" />
            <div class="ant-upload-text">更换头像</div>
          </div>
        </div>
        <div v-else>
          <loading-outlined v-if="loading"></loading-outlined>
          <plus-outlined v-else></plus-outlined>
          <div class="ant-upload-text">Upload</div>
        </div>
      </a-upload>
    </div>
    <div class="user-setting-container-info">
      <a-space direction="vertical" style="width: 100%">
        <div class="info-item">
          <label class="info-label">昵称：</label>
          <a-input
            v-model:value="username"
            placeholder="请输入昵称"
            class="info-input"
          />
          <div v-if="isUsernameChanged" class="submit-btn">
            <a-button type="link" block @click="saveUsername">保存</a-button>
          </div>
        </div>
        <div class="info-item">
          <label class="info-label">个性签名：</label>
          <a-input
            v-model:value="signature"
            placeholder="请输入个性签名"
            class="info-input"
          />
          <div v-if="isSignatureChanged" class="submit-btn">
            <a-button type="link" block @click="saveSignature">保存</a-button>
          </div>
        </div>
      </a-space>
    </div>
    <a-divider />
    <h1 class="user-setting-title">个人资料设置</h1>
    <div class="sexInfo">
      <div class="priInfo-item">
        <label class="priInfo-label">性别：</label>
        <a-radio-group v-model:value="sex" name="radioGroup" class="sex-radio">
          <a-radio value="1">男</a-radio>
          <a-radio value="2">女</a-radio>
        </a-radio-group>
        <div v-if="isSexChanged" class="submit-btn">
          <a-button @click="saveSex" type="link" block>保存</a-button>
        </div>
      </div>
    </div>
    <div class="birthInfo">
      <div class="priInfo-item">
        <label class="priInfo-label">生日：</label>
        <div style="display: flex; gap: 8px">
          <a-select
            v-model:value="selectedYear"
            style="width: 100px"
            @change="onDateChange"
          >
            <a-select-option v-for="year in years" :key="year" :value="year"
              >{{ year }}年</a-select-option
            >
          </a-select>

          <a-select
            v-model:value="selectedMonth"
            style="width: 80px"
            @change="onDateChange"
          >
            <a-select-option v-for="month in months" :key="month" :value="month"
              >{{ month }}月</a-select-option
            >
          </a-select>

          <a-select
            v-model:value="selectedDay"
            style="width: 80px"
            @change="onDateChange"
          >
            <a-select-option v-for="day in days" :key="day" :value="day"
              >{{ day }}日</a-select-option
            >
          </a-select>
        </div>

        <div v-if="isBirthdayChanged" class="submit-btn">
          <a-button type="link" block @click="saveBirthday">保存</a-button>
        </div>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { computed, onMounted, ref } from "vue";
import { LoadingOutlined, PlusOutlined } from "@ant-design/icons-vue";
import type { UploadFile } from "ant-design-vue";
import { message } from "ant-design-vue";
import { userAvatar, userInfo } from "@/api/userSetting";
import { getMinioUrl } from "@/utils/minio";
import { getCurrentUser, userLogin } from "@/api/user";
import { UserInfo } from "@/types"; // 引入接口
import { useLoginUserStore, useUserStore } from "@/store/useLoginUserStore";
import { watch } from "vue";
import { useRouter } from "vue-router";

const router = useRouter();
const loginUserStore = useLoginUserStore();

onMounted(() => {
  if (!loginUserStore.loginUser?.id) {
    router.push("/hot");
  }
});

const sex = computed({
  get() {
    return loginUserStore.loginUser?.sex || "";
  },
  set(value) {
    if (loginUserStore.loginUser) {
      loginUserStore.setLoginUser({
        ...loginUserStore.loginUser,
        sex: value,
      });
    }
  },
});
const username = computed({
  get() {
    return loginUserStore.loginUser?.username || "";
  },
  set(value) {
    if (loginUserStore.loginUser) {
      loginUserStore.setLoginUser({
        ...loginUserStore.loginUser,
        username: value,
      });
    }
  },
});

const signature = computed({
  get() {
    return loginUserStore.loginUser?.signature || "";
  },
  set(value) {
    if (loginUserStore.loginUser) {
      loginUserStore.setLoginUser({
        ...loginUserStore.loginUser,
        signature: value,
      });
    }
  },
});

const birthDay = computed({
  get() {
    return loginUserStore.loginUser?.birth_day || "";
  },
  set(value) {
    if (loginUserStore.loginUser) {
      loginUserStore.setLoginUser({
        ...loginUserStore.loginUser,
        birth_day: value,
      });
    }
  },
});
const imageUrl = ref<string>("");
const loginUser = computed(() => loginUserStore.loginUser || {});
const showCamera = ref<boolean>(false);
const uploadRef = ref(); // 获取 a-upload 组件实例

const originalUserInfo = ref<UserInfo | null>(null);
const isUsernameChanged = ref(false);
watch(
  () => loginUserStore.loginUser?.username,
  (newVal, oldVal) => {
    console.log("用户名已更新为：", newVal);
    if (oldVal === undefined) {
      isUsernameChanged.value = false; // 初始加载不显示按钮
    } else {
      isUsernameChanged.value = newVal !== oldVal;
    }
  },
  { deep: true, immediate: true }
);
const saveUsername = async () => {
  const current = loginUserStore.loginUser?.username || "";
  const original = originalUserInfo.value?.username || "";
  console.log("当前输入：", current);
  console.log("原始用户名：", original);
  if (current === original) {
    console.log("用户名未更改");
    isUsernameChanged.value = false;
    return;
  }
  if (current === "") {
    message.error("用户名不能为空");
    return;
  }
  try {
    console.log("开始修改用户名");
    const res = await userInfo({
      username: current,
    });
    if (res.data.code === 200) {
      message.success("修改成功");
      useUserStore().setUsername(res.data.data.username);
      if (originalUserInfo.value) {
        originalUserInfo.value.username = current;
      }
      isUsernameChanged.value = false;
    } else {
      message.error("修改失败");
    }
  } catch (error) {
    console.error("修改失败:", error);
    message.error("网络错误，请重试");
  }
};

const isSexChanged = ref(false);
watch(
  () => loginUserStore.loginUser?.sex,
  (newVal, oldVal) => {
    console.log("性别已更新为：", newVal);
    if (oldVal === undefined) {
      isSexChanged.value = false; // 初始加载不显示按钮
    } else {
      isSexChanged.value = newVal !== oldVal;
    }
  },
  { deep: true, immediate: true }
);
const saveSex = async () => {
  const current = loginUserStore.loginUser?.sex || "";
  const original = originalUserInfo.value?.sex || "";
  console.log("当前输入：", current);
  console.log("原始性别：", original);
  if (current === original) {
    console.log("性别未更改");
    isSexChanged.value = false;
    return;
  }
  try {
    console.log("开始修改性别");
    const res = await userInfo({
      sex: current,
    });
    if (res.data.code === 200) {
      message.success("修改成功");
      useUserStore().setSex(res.data.data.sex);
      if (originalUserInfo.value) {
        originalUserInfo.value.sex = current;
      }
      isSexChanged.value = false;
    } else {
      message.error("修改失败");
    }
  } catch (error) {
    console.error("修改失败:", error);
    message.error("网络错误，请重试");
  }
};

const isSignatureChanged = ref(false);
watch(
  () => loginUserStore.loginUser?.signature,
  (newVal, oldVal) => {
    console.log("个性签名已更新为：", newVal);
    if (oldVal === undefined) {
      isSignatureChanged.value = false; // 初始加载不显示按钮
    } else {
      isSignatureChanged.value = newVal !== oldVal;
    }
  },
  { deep: true, immediate: true }
);
const saveSignature = async () => {
  let current = loginUserStore.loginUser?.signature || "";
  const original = originalUserInfo.value?.signature || "";
  console.log("当前输入：", current);
  console.log("原始个性签名：", original);
  if (current === original) {
    console.log("个性签名未更改");
    isSignatureChanged.value = false;
    return;
  }
  try {
    console.log("开始修改个性签名");
    const res = await userInfo({
      signature: current,
    });
    if (res.data.code === 200) {
      message.success("修改成功");
      useUserStore().setSignature(res.data.data.signature);
      if (originalUserInfo.value) {
        originalUserInfo.value.signature = current;
      }
      isSignatureChanged.value = false;
    } else {
      message.error("修改失败");
    }
  } catch (error) {
    console.error("修改失败:", error);
    message.error("网络错误，请重试");
  }
};

// 年份范围（比如从当前年往前推 100 年）
const currentYear = new Date().getFullYear();
const years = Array.from({ length: 100 }, (_, i) => currentYear - i);

// 月份列表（1~12）
const months = Array.from({ length: 12 }, (_, i) => i + 1);

// 天数列表
const days = ref<number[]>([]);

// 当前选中的年月日
const selectedYear = ref<number | null>(null);
const selectedMonth = ref<number | null>(null);
const selectedDay = ref<number | null>(null);

// 构造最终生日字符串
const formattedBirthDay = ref<string>("");

// 初始化日期
onMounted(() => {
  const birthDay = loginUserStore.loginUser?.birth_day;
  if (birthDay && typeof birthDay === "string") {
    const [year, month, day] = birthDay.split("-").map(Number);
    selectedYear.value = year;
    selectedMonth.value = month;
    selectedDay.value = day;
    updateDays(year, month);
  }
});

// 监听年月变化以更新天数
watch([selectedYear, selectedMonth], ([newYear, newMonth]) => {
  if (newYear && newMonth) {
    updateDays(newYear, newMonth);
    if (
      selectedDay.value !== null &&
      selectedMonth.value !== null &&
      selectedYear.value !== null
    ) {
      if (selectedDay.value > days.value.length) {
        selectedDay.value = null;
      }
    }
  }
});

// 更新天数（根据年和月）
function updateDays(year: number, month: number) {
  const totalDays = new Date(year, month, 0).getDate();
  days.value = Array.from({ length: totalDays }, (_, i) => i + 1);
}

// 构造生日字符串
watch(
  () => [selectedYear.value, selectedMonth.value, selectedDay.value],
  () => {
    if (selectedYear.value && selectedMonth.value && selectedDay.value) {
      const year = selectedYear.value;
      const month = String(selectedMonth.value).padStart(2, "0");
      const day = String(selectedDay.value).padStart(2, "0");
      formattedBirthDay.value = `${year}-${month}-${day}`;
    } else {
      formattedBirthDay.value = "";
    }
  },
  { immediate: true }
);

// 检测是否更改
const isBirthdayChanged = ref(false);

watch(
  () => formattedBirthDay.value,
  (newVal) => {
    console.log(
      "当前输入：",
      newVal,
      "更改值",
      formattedBirthDay.value,
      "原始值",
      originalUserInfo.value?.birth_day,
      "是否更改",
      newVal !== originalUserInfo.value?.birth_day,
      "是否更改",
      newVal !== ""
    );
    if (!originalUserInfo.value || !newVal) {
      console.log("生日未更改");
      isBirthdayChanged.value = false;
    } else {
      console.log("生日已更新为：", newVal);
      isBirthdayChanged.value = newVal !== originalUserInfo.value.birth_day;
    }
  },
  { immediate: true }
);

// 保存到后端
const saveBirthday = async () => {
  try {
    console.log("开始修改生日", formattedBirthDay.value);
    const res = await userInfo({
      birth_day: formattedBirthDay.value,
    });
    console.log("用户信息:", res);
    if (res.data.code === 200) {
      console.log("修改成功  生日为", formattedBirthDay.value);
      message.success("修改成功");
      useUserStore().setBirthday(res.data.data.Birth_day);
      if (originalUserInfo.value) {
        originalUserInfo.value = {
          ...originalUserInfo.value,
          birth_day: formattedBirthDay.value,
        };
      }
      isBirthdayChanged.value = false;

      // 更新 store 中的原始数据
      loginUserStore.setLoginUser({
        ...loginUserStore.loginUser,
        birth_day: formattedBirthDay.value,
      });
    } else {
      message.error("修改失败");
    }
  } catch (error) {
    console.error("修改失败:", error);
    message.error("网络错误，请重试");
  }
};

// 手动触发上传（模拟点击）
const triggerUpload = () => {
  const el = uploadRef.value?.$el;
  if (!el) return;

  const input = el.querySelector('input[type="file"]');
  if (input) {
    input.click();
  }
};

// 上传头像逻辑
const customUpload = async (options: any) => {
  const { file, onsuccess, onerror } = options;

  try {
    // 获取原始文件（优先 originFileObj）
    const rawFile = file.originFileObj || file;

    // 校验是否是有效的文件
    if (!(rawFile instanceof Blob) || !rawFile.type.startsWith("image/")) {
      message.error("请上传有效的图片");
      return;
    }

    // 创建 FileReader 读取图片
    const reader = new FileReader();
    reader.onload = async (e) => {
      const imgSrc = e.target?.result as string;
      const img = new Image();

      img.onload = () => {
        const canvas = document.createElement("canvas");
        const ctx = canvas.getContext("2d");

        if (!ctx) {
          message.error("无法创建画布上下文");
          return;
        }

        // 设置目标尺寸为正方形（例如 512x512）
        const targetSize = 512;
        canvas.width = targetSize;
        canvas.height = targetSize;

        // 按比例缩放绘制，居中裁剪
        const scale = Math.max(targetSize / img.width, targetSize / img.height);
        const width = img.width * scale;
        const height = img.height * scale;
        const x = (targetSize - width) / 2;
        const y = (targetSize - height) / 2;

        ctx.drawImage(img, x, y, width, height);

        // 转换为 Blob 并封装成 File
        canvas.toBlob(async (blob) => {
          if (!blob) {
            message.error("图片处理失败");
            return;
          }

          const croppedFile = new File([blob], rawFile.name, {
            type: rawFile.type,
            lastModified: Date.now(),
          });

          // 构造 FormData 并上传
          const formData = new FormData();
          formData.append("file", croppedFile);

          try {
            const res = await userAvatar(formData);

            if (res.data.code === 200) {
              imageUrl.value = getMinioUrl(res.data.data);
              useUserStore().setAvatar(imageUrl.value);
              onsuccess?.(res.data, file);
              message.success("上传成功");
              window.location.reload();
            } else {
              onerror?.(new Error("上传失败"));
              message.error("上传失败");
            }
          } catch (uploadError) {
            console.error("上传错误:", uploadError);
            message.error("上传失败");
            onerror?.(uploadError);
          }
        }, "image/png"); // 可改为 image/jpeg 减小体积
      };

      img.onerror = () => {
        message.error("图片加载失败");
      };

      img.src = imgSrc;
    };

    reader.onerror = () => {
      message.error("文件读取失败");
    };

    reader.readAsDataURL(rawFile);
  } catch (error) {
    console.error("Upload error:", error);
    message.error("上传失败");
    if (typeof onerror === "function") {
      onerror(error);
    }
  }
};

const fileList = ref([]);
const loading = ref<boolean>(false);
// 加载当前用户信息
const loadCurrentUser = async () => {
  try {
    loading.value = true;
    const res = await getCurrentUser();
    if (res.data.code === 200 && res.data.data) {
      const user: UserInfo = res.data.data;
      loginUserStore.setLoginUser(user);
      originalUserInfo.value = {
        ...user,
        birth_day: user.birth_day ? user.birth_day : "",
      };
      if (user.avatar) {
        // 如果是 MinIO 的 key，用 getMinioUrl 拼接
        imageUrl.value = getMinioUrl(user.avatar);
      }
      if (user.birth_day) {
        const [year, month, day] = user.birth_day.split("-").map(Number);
        selectedYear.value = year;
        selectedMonth.value = month;
        selectedDay.value = day;
        updateDays(year, month);
      }
    }
  } catch (error) {
    console.error("获取用户信息失败:", error);
    message.error("获取用户信息失败");
  } finally {
    loading.value = false;
  }
};

onMounted(async () => {
  try {
    await loadCurrentUser();
  } catch (error) {
    console.error("加载用户信息失败:", error);
    message.error("网络错误，获取用户信息失败");
  }
});

const beforeUpload = (file: UploadFile<unknown>) => {
  const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
  if (!isJpgOrPng) {
    message.error("You can only upload JPG file!");
  }
  const fileSize = file.size ?? 0;
  const isLt2M = fileSize / 1024 / 1024 < 5;
  if (!isLt2M) {
    message.error("Image must smaller than 3MB!");
  }
  return isJpgOrPng && isLt2M;
};

onMounted(async () => {
  const token = localStorage.getItem("token");
  if (!token) {
    message.error("请先登录");
    router.push("/hot");
    return;
  }

  await loadCurrentUser();
});
</script>
<style scoped>
.user-setting-container-avatar {
  margin-top: 45px;
  display: flex;
  height: 200px;
  width: 100%; /* 占满宽度 */
}

/* 强制上传组件尺寸与 flex 居中 */
:deep(
    [data-custom-avatar-upload].avatar-uploader
      .ant-upload-select.ant-upload-select-picture-card
  ) {
  width: 136px !important;
  height: 136px !important;
  display: flex !important;
  margin: 0 auto !important;
  background-color: transparent !important;
  border-radius: 8px !important;
  overflow: hidden !important;
  border: 1px solid #398bfb !important;
}

:deep(
    .avatar-uploader
      .ant-upload-select.ant-upload-select-picture-card
      .ant-upload
  ) {
  display: flex !important;
  flex-direction: column !important;
  align-items: center !important;
  justify-content: center !important;
  width: 100% !important;
  height: 100% !important;
  padding: 0 !important;
  margin-left: 0 !important;
  cursor: pointer !important; /* 显式设置可点击 */
}

/* 图标大小 & 颜色 */
:deep(.avatar-uploader .anticon) {
  font-size: 32px !important;
  color: #999 !important;
}

/* 文字样式 */
:deep(.avatar-uploader .ant-upload-text) {
  margin-top: 8px !important;
  color: #666 !important;
  text-align: center !important;
}

.avatar-container {
  position: relative;
  width: 136px;
  height: 136px;
  border-radius: 8px;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-img {
  width: 100%;
  height: 100%;
  object-fit: cover; /* 按比例裁剪以适应容器 */
  display: block; /* 避免底部多余空白 */
  border-radius: 8px;
}

.camera-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  z-index: 2;
  border-radius: 8px;
}

.info-item {
  width: 100%;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.info-label {
  width: 100px;
  text-align: right;
  font-weight: bold;
}

.user-setting-title {
  margin-bottom: 30px;
}

.info-input {
  margin-left: 0;
  width: 70%;
}

.priInfo-item {
  margin-bottom: 35px;
  display: flex;
  justify-content: left;
  align-items: center;
  margin-left: 23px;
  gap: 8px;
}

.priInfo-label {
  width: 78px;
  text-align: right;
  font-weight: bold;
}
.submit-btn {
  display: flex;
}
.sex-radio {
  width: 20%;
}

.sexInfo .priInfo-item {
  height: 20px;
}
</style>
